package com.example.rotateimageview.slantView

import android.content.Context
import android.graphics.Camera
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import android.widget.FrameLayout

/**
 * author  : Liushuai
 * time    : 2021/8/29 21:30
 * desc    :
 */
class TouchSlantLayout  @JvmOverloads constructor(
        context: Context,
        attributeSet: AttributeSet? = null
) : FrameLayout(context, attributeSet, 0) {

    private var centerX=0f

    private var centerY=0f

    private val mCamera=Camera()

    private var canvasRotateX=0f

    private var canvasRotateY=0f


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX= (w /2).toFloat()
        centerY= (h/2).toFloat()
    }


    override fun dispatchDraw(canvas: Canvas?) {
        mCamera.apply {
            save()
            rotateX(canvasRotateX)
            rotateY(canvasRotateY)
        }

        matrix?.let {
            mCamera.getMatrix(matrix)
            mCamera.restore()

            it.preTranslate(-centerX,-centerY)
            it.postTranslate(centerX,centerY)
        }

        canvas?.save()
        canvas?.setMatrix(matrix)
        super.dispatchDraw(canvas)
        canvas?.restore()
    }
}